package cn.waka.sys.admin.service;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.waka.sys.admin.dao.ChannelDao;
import cn.waka.sys.admin.object.Channel;
import cn.waka.sys.admin.object.Page;

@Service
public class ChannelService {


    private ChannelDao channelDao;

    @Autowired
    public void setChannelDao(ChannelDao channelDao) {
        this.channelDao = channelDao;
    }

    public int save(Channel o) {
        if (o == null) {
            return 0;
        }
        if (o.getId() == 0) {
            long ch = channelDao.selectMaxChannel();
            o.setChannel(ch + "");
            return channelDao.insert(o);
        }
        return channelDao.update(o);
    }

    public int del(int id) {
        if (id == 0) {
            return 0;
        }
        return channelDao.del(id);
    }


    public Page findPage(Page p) {
        int page = p.getPage();
        int start = (page - 1) * p.getSize();
        int size = p.getSize();
        List<Map<String, Object>> list = channelDao.findPage(start, size);
        int count = channelDao.findTotal();
        p.setCount(count);
        p.setData(list);
        int totalPage = 0;
        if (count > 0 && count % p.getSize() > 0) {
            totalPage = (int) Math.floor(count / p.getSize());
            totalPage++;
        } else {
            totalPage = count / p.getSize();
        }
        if (totalPage == 0) {
            totalPage = 1;
        }
        p.setTotalPage(totalPage);

        return p;
    }

    public Map<String, Object> findById(int id) {
        if (id == 0) {
            return null;
        }
        return channelDao.getById(id);
    }

    public List<Map<String, Object>> getChannelList() {
        return channelDao.getChannelList();
    }
}
